package com.fengye.validation.config;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import javax.validation.MessageInterpolator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomMessageInterpolator implements MessageInterpolator {


    private final MessageSource messageSource;

    public CustomMessageInterpolator(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public String interpolate(String message, Context context) {
        return interpolate(message, context, LocaleContextHolder.getLocale());
    }

    @Override
    public String interpolate(String message, Context context, Locale locale) {
        return interpolateMessage(message);
    }


    private String interpolateMessage(String message) {
        String pattern = "\\{([^}]*)}";
        Matcher matcher = Pattern.compile(pattern).matcher(message);
        if (matcher.find()) {
            String code = matcher.group(1);
            message = code;
        }

        String resolvedMessage = messageSource.getMessage(message, null, LocaleContextHolder.getLocale());

        return resolvedMessage;
    }
}